/*
 * interbroker_channel_launcher.cpp
 *
 */
#include <iostream>
#include <stdlib.h>
#include <fstream>

#include "../common/Argv.h"
#include "../common/ArchivoIni.h"
#include "../common/StringUtils.h"
#include "../channel_common/ChannelCommon.h"
#include "../IPC/Sequence.h"
#include "../IPC/ClientSocket.h"
#include "../logger/logger.h"
#include "../IPC/ServerSocket.h"
#include "../IPC/ProcessAux.h"

int main(int argc, char **argv)
{
	CLogger::create("Servidor Salida Broker");
	char buffer[TAM_BUFFER];
	int puertoSalida = 0;
	ipc::ServerSocket socketSalidaPasivo;
	std::string server;

	//Toma argumentos (main)
	Argv args(argv);

	if (args.getArgc() != 2)
	{
		std::cout <<"Servidor Entrada Broker Error: Cantidad de parametros invalida."<<std::endl;
		exit(1);
	}

	std::string brokerName= args.getArg(1);

	CLogger::create("Interbroker launcher broker:"+brokerName);

	MapaIni config = ArchivoIni::parsearComoIni("brokers.ini");

	MapaIni::iterator it;

	for(it=config.begin(); it!=config.end();it++)
	{
		//Dont open channels for this broker
		if(it->first != brokerName)
		{
			std::vector<std::string> brokerParams= StringUtils::splitString(it->second,'|');

			if(brokerParams.size()<4)
			{
				CLogger::log("Malformed params",LogLevelEnum::FATAL);
				exit(1);
			}

			server = brokerParams[1];
			puertoSalida = StringUtils::StringToNumber<int>(brokerParams[3]);

			// Me conecto al puerto de Entrada del servidor.
			ipc::ClientSocket socketSalida;
			socketSalida.connect(server, puertoSalida);

			CLogger::log("Conectado al broker:" +server +":"+StringUtils::NumberToString(puertoSalida),
											LogLevelEnum::INFO);

			channel::StartComunicationMessage startMsg;
			char buffer[TAM_BUFFER];

			strcpy(startMsg.channelName,brokerName.c_str());

			memcpy(buffer,&startMsg,sizeof(startMsg));

			socketSalida.send(buffer,TAM_BUFFER);

			Argv args;
			args.pushArg(StringUtils::NumberToString(socketSalida.getFd()));
			args.pushArg(StringUtils::NumberToString(brokerName));

			ProcessAux::launchProcess("./out/channel_in_broker",1,args.getArgv());
		}
	}
	return 0;
}
